<?php

namespace App\Http\Controllers\Api\Admin;

use App\AboutUs;
use App\AgentApply;
use App\AgentList;
use App\AgentOrder;
use App\AgentSettleAccountsRecord;
use App\BasicSetting;
use App\Button;
use App\Classify;
use App\Course;
use App\CourseContent;
use App\CourseLabel;
use App\CourseStudyLenght;
use App\CourseType;
use App\CustomerClue;
use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\Wechat\WechatLogin;
use App\IntegralDetail;
use App\OrderItem;
use App\Orders;
use App\Teacher;
use App\User;
use App\UserAppointment;
use App\UserInfo;
use App\Banner;
use App\VipInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class BasicController extends Controller
{
    /**
     * 用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);
        $keyword= $request->input('keyword') ?? '';
        $isFollow = $request->input('is_follow') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;


        $users = User::where('id','>',0);

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')
                ->orWhere('realname','like','%'.trim($keyword).'%')
                ->pluck('user_id')
                ->toArray();
            $users->whereIn('id',$nickname)
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }

        if(is_numeric($isFollow)){
            if($isFollow == 0){
                $userIds = CustomerClue::whereIsSelect(1)->pluck('user_id')->toArray();
                $userIds = User::whereNotIn('id',$userIds)->pluck('id')->toArray();
            }else{
                $userIds = CustomerClue::whereIsSelect($isFollow)->pluck('user_id')->toArray();
            }
            $users = $users->whereIn('id',$userIds);
        }

        $users = $users->whereRole(0);

        $pageInfo['total']=$users->count();

        $users = $users->orderByDesc('id')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();

        if (count($users) > 0){
            /** @var User $user */
            foreach ($users as $user){
                $user->user_info=UserInfo::getUserInfo($user->id);
                $user->vip_info=VipInfo::getUserVipInfo($user->id);
                $inviteUserInfo = UserInfo::whereUserId($user->invite_user_id)->first();
                $user->invite_user_name = $inviteUserInfo->nickname ?? '';
                $user->follow_up_person_name = CustomerClue::getCustomerStaffName($user->id);
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);
    }

    /**
     * 消费用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getConsumeUserList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);
        $keyword= $request->input('keyword') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        $consumeUserIds = Orders::whereIsPay(1)->whereIsSuccess(1)->pluck('user_id')->toArray();

        $consumeUserIds = array_unique($consumeUserIds);

        $users = User::whereIn('id',$consumeUserIds);

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')
                ->orWhere('realname','like','%'.trim($keyword).'%')
                ->pluck('user_id')
                ->toArray();
            $users->whereIn('id',$nickname)
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }

        $users = $users->whereIn('id',$consumeUserIds);

        $pageInfo['total']=$users->count();

        $users = $users->orderByDesc('id')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();

        if (count($users) > 0){
            /** @var User $user */
            foreach ($users as $user){
                $user->user_info=UserInfo::getUserInfo($user->id);
                $user->vip_info=VipInfo::getUserVipInfo($user->id);
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);
    }

    /**
     * 会员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipUserList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);
        $keyword= $request->input('keyword') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        $vipUserIds = VipInfo::whereColumn('num','>','use_num')->orWhere('end_time','>',date('Y-m-d H:i:s',time()))->pluck('user_id')->toArray();

        $vipUserIds = array_unique($vipUserIds);

        $users = User::whereIn('id',$vipUserIds);

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')
                ->orWhere('realname','like','%'.trim($keyword).'%')
                ->pluck('user_id')
                ->toArray();
            $users->whereIn('id',$nickname)
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }

        $users = $users->whereIn('id',$vipUserIds);

        $pageInfo['total']=$users->count();

        $users = $users->orderByDesc('id')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();

        if (count($users) > 0){
            /** @var User $user */
            foreach ($users as $user){
                $user->user_info=UserInfo::getUserInfo($user->id);
                $user->vip_info=VipInfo::getUserVipInfo($user->id);
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);
    }

    /**
     * 获取用户购买过的课程
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserBuyCourseList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $userId = $request->input('user_id',0);
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);

        $buy_ids=[];
        if($userId){
            $is_payed_id=Orders::whereUserId($userId)
                ->whereIsPay(1)
                ->whereIsSuccess(1)
                ->pluck('id')->toArray();
            $buy_ids = OrderItem::whereUserId($userId)->whereIn('order_id',$is_payed_id)->pluck('course_id')->toArray();
        }

        $page_info = [
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;

        $data = Course::whereIn('id',$buy_ids);

        $page_info['total']=$data->count();

        $data=$data->orderBy('sort')
            ->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();

        if (count($data) > 0){
            foreach ($data as $item){
                $item->thumb_url = FileManager::getImgUrl($item->thumb_id);
                $item->study_type_name = $item->getStudyTypeName($item->study_type);
                $item->label_arr = CourseLabel::getCourseLabel($item->id);
                $item->type_arr = CourseType::getCourseType($item->id);
                $item->order_info = null;
                $orderItem = OrderItem::whereUserId($userId)->whereIn('order_id',$is_payed_id)->whereCourseId($item->id)->first();
                if($orderItem){
                    $order = Orders::whereId($orderItem->order_id)->whereIsPay(1)->whereIsSuccess(1)->first();
                    if($order){
                        $order->vip_type_name = VipInfo::getVipTypeName($order->vip_type);
                        if($order->pay_way == 'wechatpay'){
                            $order->pay_way_name = '微信支付';
                        }elseif($order->pay_way == 'alipay'){
                            $order->pay_way_name = '支付宝支付';
                        }elseif($order->pay_way == 'integralpay'){
                            $order->pay_way_name = '积分支付';
                        }

                        if($order->package_id != 0){
                            $order->type_name = '套餐订单';
                        }elseif($order->group_id != 0){
                            $order->type_name = '拼团订单';
                        }else{
                            $order->type_name = '常规订单';
                        }

                        $item->order_info = $order;



                    }
                }

                $item->cumulative_study_time = CourseStudyLenght::getUserStudyCourseLength($userId,$item->id);
            }
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }

    /**
     * 获取用户的积分记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIntegralRecordList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $userId = $request->input('user_id',0);
        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);
        $type   = $request->input('type','');

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        /** @var IntegralDetail $integralRecord */
        $integralRecordList = IntegralDetail::whereUserId($userId);

        if($type != '' && in_array($type,['add','use'])){
            $integralRecordList->whereType($type);
        }

        $page_info['total'] = $integralRecordList->count();

        $integralRecordList = $integralRecordList->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();

        if(count($integralRecordList) > 0){
            foreach ($integralRecordList as $integralRecord) {
                if($integralRecord->type == 'add'){
                    $integralRecord->type_name = '获得';
                }elseif($integralRecord->type == 'use'){
                    $integralRecord->type_name = '使用';
                }else{
                    $integralRecord->type_name = $integralRecord->type;
                }
            }
        }

        $addTotalIntegral = IntegralDetail::whereUserId($userId)->whereType('add')->sum('integral_num');
        $useTotalIntegral = IntegralDetail::whereUserId($userId)->whereType('use')->sum('integral_num');

        $userInfo = UserInfo::whereUserId($userId)->first();
        $integralBalance = $userInfo ? $userInfo->integral : 0;


        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$integralRecordList,'integral_balance' => $integralBalance,'use_integral' => $useTotalIntegral]);
    }

    /**
     * banner列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBannerList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        /** @var Banner $item */
        $banner = Banner::whereNull('deleted_at');

        $page_info['total'] = $banner->count();
        $banner = $banner->orderBy('sort','asc')
            ->orderBy('created_at','desc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($banner) > 0){
            foreach ($banner as $item){
                $item->img_url  =FileManager::getImgUrl($item->img_id);
            }
        }

        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$banner]);

    }

    /**
     * banner详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBannerDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->input('id');

        $banner = Banner::whereId($id)->first();
        if ($banner){
            $banner->img_url=FileManager::getImgUrl($banner->img_id);
        }

        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$banner]);
    }

    /**
     * 设置banner
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setBanner(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id     = $request->input('id');
        $img_id = $request->input('img_id');
        $title  = $request->input('title');
        $link_url=$request->input('link_url');
        $sort   = $request->input('sort');
        $status = $request->input('status');

        $banner=Banner::whereId($id)->first();
        if (!$banner)
            $banner=new Banner();

//        if ($title)
            $banner->title=$title ?? '';
//        if ($img_id)
            $banner->img_id =$img_id ?? 0;
//        if ($link_url)

        $banner->link_url=$link_url ?? '';

//        if ($sort)
            $banner->sort   =$sort ?? 0;
        $banner->status =1;
        $banner->location ='index';
        $banner->save();
        return response()->json(['level'=>'success','message'=>'操作成功','data'=>$banner]);
    }

    /**
     * 删除banner
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delBanner(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id     = $request->input('id');

        $banner = Banner::whereId($id)->first();
        if (!$banner)
            return response()->json(['level'=>'error','message'=>'banner不存在']);

        $banner->delete();

        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    /**
     * 功能区列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getButtonList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        /** @var Button $button */
        $buttonList = Button::whereNull('deleted_at');

        $page_info['total'] = $buttonList->count();

        $buttonList = $buttonList->orderBy('created_at','desc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if(count($buttonList) > 0){
            foreach ($buttonList as $button) {
                $button->img_url = FileManager::getImgUrl($button->img_id);

                $button->classify_name = Classify::getClassifyName($button->classify_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $buttonList,'page_info' => $page_info]);
    }

    /**
     * 功能区详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getButtonDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->input('id') ?? 0;

        $button = Button::whereId($id)->first();
        if($button){
            $button->img_url = FileManager::getImgUrl($button->img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $button]);
    }

    /**
     * 设置功能区
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setButton(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $title      = $request->input('title') ?? '';
        $linkUrl    = $request->input('link_url') ?? '';
        $imgId      = $request->input('img_id') ?? 0;
        $level      = $request->input('level') ?? 0;
        $sort       = $request->input('sort') ?? 0;
        $classifyId = $request->input('classify_id') ?? 0;
        $id         = $request->input('id') ?? 0;

        $button = Button::whereId($id)->first();
        if(!$button)
            $button = new Button();

        $button->classify_id         = $classifyId;
        $button->title               = $title;
        $button->level               = $level;
        $button->link_url            = $linkUrl;
        $button->img_id              = $imgId;
        $button->sort                = $sort;
        $button->status              = 1;
        $button->location            = 'index';
        $button->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $button]);
    }

    /**
     * 删除功能区
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delButton(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->input('id') ?? 0;

        $button = Button::whereId($id)->first();
        if(!$button)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $button->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $button]);
    }

    /**
     * 获取个人合作协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPersonalCooperationAgreement(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $personalCooperationAgreement = AboutUs::whereType('personal_cooperation_agreement')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $personalCooperationAgreement]);
    }

    /**
     * 设置个人合作协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPersonalCooperationAgreement(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $detail = $request->input('detail') ?? '';

        $personalCooperationAgreement = AboutUs::whereType('personal_cooperation_agreement')->first();
        if(!$personalCooperationAgreement)
            $personalCooperationAgreement = new AboutUs();

        $personalCooperationAgreement->type = 'personal_cooperation_agreement';
        $personalCooperationAgreement->detail = $detail;
        $personalCooperationAgreement->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $personalCooperationAgreement]);
    }

    /**
     * 获取企业合作协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseCooperationAgreement(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseCooperationAgreement = AboutUs::whereType('enterprise_cooperation_agreement')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseCooperationAgreement]);
    }

    /**
     * 设置企业合作协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setEnterpriseCooperationAgreement(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $detail = $request->input('detail') ?? '';

        $enterpriseCooperationAgreement = AboutUs::whereType('enterprise_cooperation_agreement')->first();
        if(!$enterpriseCooperationAgreement)
            $enterpriseCooperationAgreement = new AboutUs();

        $enterpriseCooperationAgreement->type = 'enterprise_cooperation_agreement';
        $enterpriseCooperationAgreement->detail = $detail;
        $enterpriseCooperationAgreement->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $enterpriseCooperationAgreement]);
    }

    /**
     * 获取联系客服
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getContactCustomerService(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $contactCustomerService = AboutUs::whereType('customer_service')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $contactCustomerService]);
    }

    /**
     * 设置联系客服
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setContactCustomerService(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $detail = $request->input('detail') ?? '';

        $customerService = AboutUs::whereType('customer_service')->first();
        if(!$customerService)
            $customerService = new AboutUs();

        $customerService->type = 'customer_service';
        $customerService->detail = $detail;
        $customerService->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $customerService]);
    }

    /**
     * 获取关于我们
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAboutUs(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $aboutUs = AboutUs::whereType('about_us')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $aboutUs]);
    }

    /**
     * 设置关于我们
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAboutUs(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $detail = $request->input('detail') ?? '';

        $aboutUs = AboutUs::whereType('about_us')->first();
        if(!$aboutUs)
            $aboutUs = new AboutUs();

        $aboutUs->type                   = 'about_us';
        $aboutUs->detail                 = $detail;
        $aboutUs->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $aboutUs]);
    }

    public function setVideoStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $status=$request->input('status');

        $setting = BasicSetting::whereType('video')->first();

        if (!$setting){
            $setting        = new BasicSetting();
            $setting->type  = 'video';
        }
        $setting->status    = $status ? 1 : 0;
        $setting->save();
        return response()->json(['level' => 'success','message' => '设置成功','data' => $setting]);
    }

    public function getVideoStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);


        $setting = BasicSetting::whereType('video')->first();

        if (!$setting){
            $setting        = new BasicSetting();
            $setting->type  = 'video';
            $setting->save();
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $setting]);
    }

    /**
     * 功能区路径
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSectionUrl(Request $request){
        $data = [
            (object)[
                'name' => '首页',
                'link_url' => 'pages/index/index',
                'level' => 1,
            ],
            (object)[
                'name' => '服务类型',
                'link_url' => 'pages/classify/classify',
                'level' => 2,
            ],
            (object)[
                'name' => '服务列表',
                'link_url' => 'pages/course/course',
                'level' => 1,
            ],
            (object)[
                'name' => '资讯列表',
                'link_url' => 'pages/news/news',
                'level' => 1,
            ],
            (object)[
                'name' => '代理人列表',
                'link_url' => 'pages/agentAll/agentAll',
                'level' => 2,
            ],
            (object)[
                'name' => '宣传介绍',
                'link_url' => 'pages/publicity/publicity',
                'level' => 2,
            ],
        ];

//        /** @var Classify $DemandClassify */
//        $DemandClassifies = Classify::whereType('demand')->orderBy('created_at','desc')->get();
//        if(count($DemandClassifies) > 0){
//            foreach($DemandClassifies as $DemandClassify){
//                $child = (object)[
//                    'name' => $DemandClassify->name,
//                    'link_url' => '/pages/needsClass/needsClass?classify_id='.$DemandClassify->id,
//                    'level' => '2',
//                ];
//
//                array_push($data,$child);
//            }
//        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }

    /**
     * 代理人申请列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAgentApplyList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page   = $request->input('page',1);
        $limit  = $request->input('limit',16);

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page=$page-1;

        /** @var AgentApply $agentApply */
        $agentApplyList = AgentApply::where('id','>',0);

        $pageInfo['total'] = $agentApplyList->count();

        $agentApplyList = $agentApplyList->orderByDesc('id')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();
        if(count($agentApplyList) > 0){
            foreach ($agentApplyList as $agentApply) {
                if($agentApply->type == 'personal'){
                    $agentApply->type_name = '个人';
                }elseif($agentApply->type == 'enterprise'){
                    $agentApply->type_name = '企业';
                }else{
                    $agentApply->type_name = $agentApply->type;
                }

                if($agentApply->review == 1){
                    $agentApply->review_name = '通过';
                }elseif($agentApply->review == 2){
                    $agentApply->review_name = '拒绝';
                }else{
                    $agentApply->review_name = '待审核';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $agentApplyList,'page_info' => $pageInfo]);
    }

    /**
     * 审核代理人申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function reviewAgent(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $type          = $request->input('type') ?? 'refuse';
        $agentApplyId  = $request->input('agent_apply_id') ?? 0;

        $agentApply = AgentApply::whereId($agentApplyId)->first();
        if(!$agentApply)
            return response()->json(['level' => 'error','message' => '该申请不存在']);

        if($agentApply->review > 0)
            return response()->json(['level' => 'error','message' => '该申请已被处理，请勿重复操作！']);

        $user = User::whereId($agentApply->user_id)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '下单用户不存在']);

        if($type == 'pass'){
            $agentApply->review = 1;
            $agentApply->save();

            $newAgent = new AgentList();
            $newAgent->user_id                      = $agentApply->user_id;
            $newAgent->realname                     = $agentApply->realname;
            $newAgent->id_card                      = $agentApply->id_card;
            $newAgent->type                         = $agentApply->type;
            $newAgent->company_name                 = $agentApply->company_name;
            $newAgent->unified_social_credit_code   = $agentApply->unified_social_credit_code;
            $newAgent->contacts_people              = $agentApply->contacts_people;
            $newAgent->phone                        = $agentApply->phone;
            $newAgent->save();

            $data = [
                'touser' => $user->wx_openid,
                'template_id' => 'egbaGlk7YOldSOdy89IZmPfo0-GK1e9cjP0nHHPF-Ew',
                'page' => 'pages/agentPromotion/agentPromotion',
                'data' => [
                    "phrase1" => [
                        "value" => '通过'
                    ],
                    "date2" => [
                        "value" => date("Y-m-d H:i")
                    ],
                    "thing3" => [
                        "value" => '恭喜您通过审核'
                    ]
                ]
            ];
            WechatLogin::sendSubscribeMessage($data);
        }else{
            $agentApply->review = 2;
            $agentApply->save();

            $data = [
                'touser' => $user->wx_openid,
                'template_id' => 'egbaGlk7YOldSOdy89IZmPfo0-GK1e9cjP0nHHPF-Ew',
                'page' => 'pages/agentPromotion/agentPromotion',
                'data' => [
                    "phrase1" => [
                        "value" => '不通过'
                    ],
                    "date2" => [
                        "value" => date("Y-m-d H:i")
                    ],
                    "thing3" => [
                        "value" => '很遗憾未通过审核'
                    ]
                ]
            ];
            WechatLogin::sendSubscribeMessage($data);
        }

        return response()->json(['level' => 'success','message' => '操作成功']);
    }

    /**
     * 推广订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAgentOrderList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit = $request->input('limit') ?? 20;
        $page = $request->input('page') ?? 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var AgentOrder $agentOrder */
        $agentOrderList = AgentOrder::where('id','>',0);

        $pageInfo['total'] = $agentOrderList->count();

        $agentOrderList = $agentOrderList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($agentOrderList) > 0){
            foreach ($agentOrderList as $agentOrder) {
                $agentOrder->course_name = '';
                $agentOrder->order_pay_amount = 0;
                $agentOrder->commission_ratio = 0 . '%';
                $order = Orders::whereOrderNum($agentOrder->order_num)->first();
                if($order){
                    $orderItem = OrderItem::whereOrderId($order->id)->first();
                    if($orderItem){
                        $course = Course::whereId($orderItem->course_id)->first();
                        $agentOrder->course_name = $course ? $course->name : '';
                        $agentOrder->commission_ratio = $course ? $course->first_ratio * 100 . '%' : 0 . "%";
                    }

                    $agentOrder->order_pay_amount = $order->pay_amount;
                }

                $orderUserInfo = CommonManager::getUserBasicInfo($agentOrder->buyer_user_id);
                $agentOrder->order_user_name = $orderUserInfo ? $orderUserInfo['nickname'] : '';
                $agentOrder->order_user_photo_url = $orderUserInfo ? $orderUserInfo['photo_url'] : '';

                $agentOrder->invite_user_name = '';
                $agentOrder->invite_user_photo_url = '';
                $agentOrder->invite_people_type = '未知';
                if($agentOrder->buyer_user_id == $agentOrder->son_agent_user_id){
                    $inviteUserInfo = CommonManager::getUserBasicInfo($agentOrder->agent_user_id);
                    $agentOrder->invite_user_name = $inviteUserInfo ? $inviteUserInfo['nickname'] : '';
                    $agentOrder->invite_user_photo_url = $inviteUserInfo ? $inviteUserInfo['photo_url'] : '';
                    $agentOrder->invite_people_type = '一级代理商';
                }else{
                    $inviteUserInfo = CommonManager::getUserBasicInfo($agentOrder->son_agent_user_id);
                    $agentOrder->invite_user_name = $inviteUserInfo ? $inviteUserInfo['nickname'] : '';
                    $agentOrder->invite_user_photo_url = $inviteUserInfo ? $inviteUserInfo['photo_url'] : '';
                    $agentOrder->invite_people_type = '二级代理商';
                }

                if($agentOrder->status == 1){
                    $agentOrder->status_name = '已到账';
                }elseif($agentOrder->status == 2){
                    $agentOrder->status_name = '已退单';
                }else{
                    $agentOrder->status_name = '未到账';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $agentOrderList,'page_info' => $pageInfo]);
    }

    /**
     * 获取代理人列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAgentList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $agentList = AgentList::all();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $agentList]);
    }

    /**
     * 获取结算记录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAgentSettleAccountsRecordList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit = $request->input('limit') ?? 20;
        $page = $request->input('page') ?? 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        /** @var AgentSettleAccountsRecord $agentSettleAccountRecord */
        $agentSettleAccountRecordList = AgentSettleAccountsRecord::where('id','>',0);

        $pageInfo['total'] = $agentSettleAccountRecordList->count();

        $agentSettleAccountRecordList = $agentSettleAccountRecordList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($agentSettleAccountRecordList) > 0){
            foreach ($agentSettleAccountRecordList as $agentSettleAccountRecord) {
                $agent = AgentList::whereUserId($agentSettleAccountRecord->agent_user_id)->first();
                if($agent){
                    if($agent->type == 'personal'){
                        $agent->type_name = '个人';
                    }elseif($agent->type == 'enterprise'){
                        $agent->type_name = '企业';
                    }else{
                        $agent->type_name = $agent->type;
                    }
                }

                $agentSettleAccountRecord->agent_info = $agent;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $agentSettleAccountRecordList,'page_info' => $pageInfo]);
    }

    /**
     * 设置结算记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAgentSettleAccountsRecord(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $agentUserId = $request->input('agent_user_id') ?? 0;
        $amount      = $request->input('amount') ?? 0;

        $agent = AgentList::whereUserId($agentUserId)->first();
        if(!$agent)
            return response()->json(['level' => 'error','message' => '代理人不存在']);

        if($agent->balance < $amount)
            return response()->json(['level' => 'error','message' => '代理人账户余额不足']);

        $newSettleAccountsRecord = new AgentSettleAccountsRecord();
        $newSettleAccountsRecord->agent_user_id = $agent->user_id;
        $newSettleAccountsRecord->amount        = $amount;
        $newSettleAccountsRecord->save();

        $agent->balance -= $amount;
        $agent->save();

        return response()->json(['level' => 'success','message' => '操作成功','data' => $newSettleAccountsRecord]);
    }

    /**
     * 用户预约线下列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserAppointmentList(Request $request) {
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = $request->input('page') ?? 1;
        $limit   = $request->input('limit') ?? 10;
        $keyword = $request->input('keyword') ?? '';
        $status  = $request->input('status') ?? '';

        $pageInfo = [
            'page' => $page,
            'limit' => $limit
        ];
        $page = $page-1;

        $appointments = UserAppointment::where('id','>',0);

        if(is_numeric($status)) {
            $appointments = $appointments->whereStatus($status);
        }

        if($keyword != ''){
//            $realname = UserInfo::where('realname','like','%'.trim($keyword).'%')
//                ->pluck('user_id')
//                ->toArray();
//            $appointments->whereIn('user_id', $realname)
//                ->orWhere('phone','like','%'.trim($keyword).'%');
            $appointments->where('realname','like', '%'.trim($keyword).'%')
                ->orWhere('phone','like','%'.trim($keyword).'%');
        }
        $pageInfo['total'] = $appointments->count();

        $appointments = $appointments->orderByDesc('id')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();

        return response()->json(['level'=>'success','message'=>'success','data'=>$appointments,'page_info'=>$pageInfo]);
    }

    /**
     * 切换预约状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeAppointmentStatus(Request $request) {
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;
        $status = $request->get('status') ?? '';

        /** @var UserAppointment $appointment */
        $appointment = UserAppointment::whereId($id)->first();
        if(!$appointment)
            return response()->json(['level' => 'error','message' => '预约不存在']);

        if($status == '' || is_null($status))
            return response()->json(['level' => 'error','message' => '状态不能为空']);

        if($appointment->status != $status) {
            if(!in_array($status, [0, 1, 2]))
                return response()->json(['level' => 'error','message' => '状态值有误']);
            $appointment->status = $status;
            $appointment->save();
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $appointment]);
    }
}
